package com.framework.test.listeners;

import com.framework.test.exceptions.AutomationException;
import com.framework.test.utils.ConfigurationManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;
import org.testng.Reporter;

public class Retry implements IRetryAnalyzer {
    private static final Logger logger = LogManager.getLogger(Retry.class);
    private int retryCount = 0;
    private static final int maxRetryCount;
    private static final boolean enableRetryOnDataProvider;

    static {
        try {
            maxRetryCount = Integer.parseInt(ConfigurationManager.getProperty("maxRetryCount"));
        enableRetryOnDataProvider = Boolean.parseBoolean(
                ConfigurationManager.getProperty("enableRetryOnDataProvider", "false"));
        } catch (AutomationException e) {
            throw new RuntimeException("Failed to load retry configuration", e);
        }
    }

    @Override
    synchronized public boolean retry(ITestResult result) {
        String testName = result.getMethod().getMethodName();
        String className = result.getTestClass().getName();
        
        // 检查是否为数据驱动测试，如果配置不允许重试则跳过
        if (!enableRetryOnDataProvider && result.getParameters().length > 0) {
            logger.info("Skipping retry for data-driven test: {}.{}", className, testName);
            return false;
        }
        
        if (retryCount < maxRetryCount) {
            retryCount++;
            logger.warn("Test failed: {}.{}, attempting retry {}/{}", 
                className, testName, retryCount, maxRetryCount);
            logger.debug("Failure reason: {}", result.getThrowable().getMessage());
            
            Reporter.setCurrentTestResult(result);
            Reporter.log(String.format("Retrying test %s.%s - Attempt %d/%d", 
                className, testName, retryCount, maxRetryCount));
            return true;
        }
        
        logger.error("Test failed after {} retries: {}.{}", maxRetryCount, className, testName);
        return false;
    }
    
    /**
     * 获取当前重试次数
     * @return 重试次数
     */
    public int getRetryCount() {
        return retryCount;
    }
    
    /**
     * 获取最大重试次数
     * @return 最大重试次数
     */
    public static int getMaxRetryCount() {
        return maxRetryCount;
    }
}